/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2022-04-12 16:58:33
 * @LastEditTime: 2023-06-25 17:21:24
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 抽屉控制
 * @FilePath: \vue3-element-plus-web\src\store\modules\drawer.js
 * @Copyright 版权声明
 */
import { ElNotification, ElMessageBox } from 'element-plus'
import { GLOBAL_MODULE } from '@/config/module'

const drawer = {
  state: {
    visible: false, // 抽屉 显示/隐藏 标记
    /**
     * 是否重载页面标识
     * @type Boolean / Object
     *    Boolean   true：重载 ， false：不重载
     *    Object  {
     *              reload: true重载  false不重载,
     *              ...其他参数
     *            }
     */
    reloadPage: false,
    // 抽屉 loading 状态
    loading: false,
    // 当前打开的drawer所属模块信息
    current: {
      module: '', // 模块标识
      moduleName: '', // 模块名称
      drawerComponents: '', // 模块所在组件
      drawerComponentsName: '', // 模块所在组件 的 name
      drawerType: '', // 抽屉类型，如：CREATE、UPDATE、DETAIL
      drawerTypeName: '', // 抽屉标题名称
      drawerSize: '60%', // Drawer 窗体的大小, 当使用 number 类型时, 以像素为单位, 当使用 string 类型时, 请传入 'x%', 否则便会以 number 类型解释
      closeConfirm: false, // 是否在关闭 Drawer时 二次确认
      params: {} // 传递给抽屉的参数
    },
    history: [], // drawer跳转的历史栈
    drawerKeepAlive: {} // 被 keep-alive 缓存的抽屉组件， 一层为模块组件，二层为模块内页面组件
  },

  mutations: {
    SET_VISIBLE: (state, value) => {
      state.visible = value
    },
    SET_LOADING: (state, value) => {
      state.loading = value
    },
    SET_HISTORY: (state, value) => {
      state.history = value
    },
    SET_CURRENT: (state, value) => {
      state.current = value
    },
    SET_RELOAD_PAGE: (state, value) => {
      state.reloadPage = value
    },
    SET_DRAWER_KEEP_ALIVE: (state) => {
      if ((state.history).length === 0) {
        // 如果已打开的 drawer 为空则清空 keep-alive 缓存
        state.drawerKeepAlive = {}
      } else {
        state.drawerKeepAlive = {}
        // 遍历已打开的 drawer
        for (const item of state.history) {
          // 如果 drawerComponentsName 已定义 并且 drawerComponentsName 不等于 空
          if ((typeof item.drawerComponentsName !== 'undefined') && (item.drawerComponentsName !== '')) {
            if (typeof state.drawerKeepAlive[item.drawerComponentsName] !== 'undefined') {
              state.drawerKeepAlive[item.drawerComponentsName].push(item.drawerType)
            } else {
              state.drawerKeepAlive[item.drawerComponentsName] = []
              state.drawerKeepAlive[item.drawerComponentsName].push(item.drawerType)
            }
          }
        }
      }
    }
  },

  actions: {
    // 返回上一个 drawer
    GoBackDrawer({ state, commit }, params) {
      // 是否自动退出：不判断 closeConfirm
      const auto = params.auto || false
      return new Promise((resolve, reject) => {
        if (auto === false && state.current.closeConfirm === true) {
          ElMessageBox.confirm('当前页面可能存在未保存内容，直接离开内容将不被保存', '确认要离开本页面吗？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              // 设置history
              const history = state.history
              history.splice(history.length - 1, 1)
              commit('SET_HISTORY', history)
              // 设置keep-alive
              commit('SET_DRAWER_KEEP_ALIVE')
              // 设置当前 drawer  配置
              const current = history[history.length - 1]
              commit('SET_CURRENT', current)
              resolve()
            })
            .catch(() => {
              reject()
              // catch error
            })
        } else {
          // 设置history
          const history = state.history
          history.splice(history.length - 1, 1)
          commit('SET_HISTORY', history)
          // 设置keep-alive
          commit('SET_DRAWER_KEEP_ALIVE')
          // 设置当前 drawer  配置
          const current = history[history.length - 1]
          commit('SET_CURRENT', current)
          resolve()
        }
      })
    },
    // 设置 drawer loading状态
    SetDrawerloading({ commit }, state = false) {
      commit('SET_LOADING', state)
    },
    // 设置 是否重载页面标识 为 true
    /**
     * 设置 是否重载页面标识
     * @param {Boolean / Object} state
     * Boolean ： true / false
     * Object ：  {
     *              reload: true / false,
     *              ...
     *            }
     */
    SetReloadPage({ commit }, state = true) {
      commit('SET_RELOAD_PAGE', state)
    },
    // 打开抽屉
    ShowDrawer({ state, commit }, { module = '', type = '', params = {}, size = '30%' }) {
      return new Promise((resolve, reject) => {
        // console.log('---', module)
        // console.log('---', type)
        // console.log('---', params)
        // console.log(GLOBAL_MODULE)
        // console.log(GLOBAL_MODULE[module])
        if (typeof GLOBAL_MODULE[module] === 'undefined') {
          ElNotification({
            title: '错误提示',
            message: `${module}模块不存在， 可在 /src/config/module.js 内进行配置`,
            type: 'error'
          })
          reject()
          return
        }
        if (typeof GLOBAL_MODULE[module]['drawer'] === 'undefined') {
          ElNotification({
            title: '错误提示',
            message: `${module}模块缺少drawer节点， 可在 /src/config/module.js 内进行配置`,
            type: 'error'
          })
          reject()
          return
        }
        if (typeof GLOBAL_MODULE[module]['drawer']['components'] === 'undefined') {
          ElNotification({
            title: '错误提示',
            message: `${module}模块的drawer节点缺少components节点， 可在 /src/config/module.js 内进行配置`,
            type: 'error'
          })
          reject()
          return
        }
        if (typeof GLOBAL_MODULE[module]['drawer']['type'] === 'undefined') {
          ElNotification({
            title: '错误提示',
            message: `${module}模块的drawer节点缺少type节点， 可在 /src/config/module.js 内进行配置`,
            type: 'error'
          })
          reject()
          return
        }
        if (typeof GLOBAL_MODULE[module]['drawer']['type'][type] === 'undefined') {
          ElNotification({
            title: '错误提示',
            message: `${module}模块的drawer节点的type节点，缺少${type}节点， 可在 /src/config/module.js 内进行配置`,
            type: 'error'
          })
          reject()
          return
        }
        const currentModule = GLOBAL_MODULE[module] // 当前模块信息
        const currentType = GLOBAL_MODULE[module]['drawer']['type'][type] // 当前抽屉类型信息
        const components = GLOBAL_MODULE[module]['drawer']['components'] // 当前抽屉组件
        const componentsName = GLOBAL_MODULE[module]['drawer']['componentsName'] || '' // 当前抽屉组件 的 name 的 name

        let drawerSize = size
        if (typeof currentType.size !== 'undefined' && currentType.size !== '30%') {
          drawerSize = currentType.size
        }

        const current = {
          module: currentModule.value,
          moduleName: currentModule.name,
          drawerComponents: components,
          drawerComponentsName: componentsName,
          drawerType: currentType.value,
          drawerTypeName: currentType.name,
          drawerSize,
          closeConfirm: currentType.closeConfirm || false,
          params
        }

        // 设置当前 drawer  配置
        commit('SET_CURRENT', current)
        // 设置显示状态为true
        commit('SET_VISIBLE', true)
        // 设置 是否重载页面标识 为 false
        commit('SET_RELOAD_PAGE', false)
        // 设置history
        const history = state.history
        history.push(current)
        commit('SET_HISTORY', history)
        // 设置keep-alive
        commit('SET_DRAWER_KEEP_ALIVE')
        resolve()
      })
    },
    //
    /**
     * @description 关闭抽屉
     * @param {} param0
     * @param {*.direct} Boolean 如果为true则直接关闭，如果为false则先判断是否有未保存数据进行提示二次确认
     * @returns Promise
     */
    CloseDrawer({ commit, state }, params = {}) {
      const direct = typeof params.direct === 'undefined' ? true : params.direct
      const closeConfirm = state.current.closeConfirm
      return new Promise((resolve, reject) => {
        // 如果为true则直接关闭
        if (direct === true) {
          // 设置history
          commit('SET_HISTORY', [])
          // 设置keep-alive
          commit('SET_DRAWER_KEEP_ALIVE')
          // 设置显示状态为false
          commit('SET_VISIBLE', false)
          resolve()
        } else {
          if (closeConfirm === true) {
            ElMessageBox.confirm('当前页面可能存在未保存内容，直接离开内容将不被保存', '确认要离开本页面吗？', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                // 设置history
                commit('SET_HISTORY', [])
                // 设置keep-alive
                commit('SET_DRAWER_KEEP_ALIVE')
                // 设置显示状态为false
                commit('SET_VISIBLE', false)
                resolve()
              })
              .catch(() => {
                reject()
                // catch error
              })
          } else {
            commit('SET_VISIBLE', false)
            resolve()
          }
        }
      })
    }
  }
}

export default drawer
